<template>
  <ele-modal
    form
    :width="460"
    title="设定学生所属辅导员"
    :body-style="{ paddingTop: '8px' }"
    :model-value="modelValue"
    @update:modelValue="updateModelValue">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      @submit.prevent="">
      <el-form-item label="辅导员" prop="counsellorCode">
        <el-select
          v-model="form.counsellorCode"
          clearable
          filterable
          style="width: 100%"
          placeholder="请选择辅导员"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #999; font-size: 13px">{{
                item.ext
              }}</span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>


<script setup>
import {ref, reactive} from 'vue';
import {useFormData} from '@/utils/use-form-data';

import {getGrade, getDepartment, getMajor, getUser} from '@/api/manage/student/admin/common.js';

import {EleMessage} from "ele-admin-plus";
import {setStudentLead} from "@/api/manage/student/admin/index.js";

const emit = defineEmits(['done', 'update:modelValue']);

const props = defineProps({
  /** 是否打开弹窗 */
  modelValue: Boolean,
  //勾选的学生id序列
  data: Array
});

/** 更新modelValue */
const updateModelValue = (value) => {
  emit('update:modelValue', value);
};

/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  counsellorCode: '',
});
/** 请求状态 */
const loading = ref(false);

/** 表单实例 */
const formRef = ref(null);

/** 表单验证规则 */
const rules = reactive({
  counsellorCode: [
    {required: true, message: '请选择一个辅导员', trigger: 'blur'},
  ]
});

/** 用户下拉列表数据 */
const userOptions = ref([]);
/** 初始化用户下拉列表数据 */
const initUser = () => {
  getUser().then((response) => {
    userOptions.value = response.data;
  });
};

const save = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return;
    }
    loading.value = true;
    let params = {
      counsellorCode: form.counsellorCode,
      studentIds: [...props.data]
    };
    setStudentLead(params).then(res => {
      loading.value = false;
      EleMessage.success("操作成功");
      updateModelValue(false);
      emit('done');
    }).catch((e) => {
      loading.value = false;
      EleMessage.error(e.message);
    });
  });
}




initUser();
</script>

<style>

</style>
